﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;

namespace BELT
{
    [Cmdlet("Navigate", "IEBrowser")]
    public class NavigateIEBrowserCommand : Cmdlet
    {
        private Object _selectIE = null;
        private string _url = "";
        [Parameter(Mandatory = false, ValueFromPipeline = false)]
        public Object IEBrowser
        {
            get
            {
                return _selectIE;
            }
            set
            {
                _selectIE = value;
            }
        }
        [Parameter(Mandatory = true, ValueFromPipeline = false, Position = 0)]
        public string URL
        {
            get
            {
                return _url;
            }
            set
            {
                _url = value;
            }
        }
        [Parameter(ValueFromPipeline = false)]
        public SwitchParameter WaitIE { set; get; }

        protected override void BeginProcessing()
        {
            base.BeginProcessing();
            if (_selectIE == null)
            {
                _selectIE = NewIEBrowserCommand.IEHandle;
            }
            else
            {
                PSObject psObj = (PSObject)_selectIE;
                _selectIE = psObj.BaseObject;
            }
            if (_selectIE == null)
            {
                this.ThrowTerminatingError(new ErrorRecord(new EntryPointNotFoundException("No IEBrowser object specified."), "E001", ErrorCategory.ObjectNotFound, null));
            }
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            Type objType = _selectIE.GetType();
            objType.InvokeMember("Navigate", BindingFlags.InvokeMethod, null, _selectIE, new object[1] { _url });
            if (WaitIE.IsPresent) {
                WaitIEBrowserCommand.Wait();
            }
        }
        protected override void EndProcessing()
        {
            base.EndProcessing();
        }
    }
}
